package com.inspur.edp.formserver.vmmanager.validate.operation;

import com.alibaba.druid.util.StringUtils;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.action.ViewModelAction;
import com.inspur.edp.formserver.viewmodel.action.mappedcdp.MappedCdpActionParameter;
import com.inspur.edp.formserver.viewmodel.exception.ViewModelException;
import com.inspur.edp.formserver.vmmanager.exception.VoManagerErrorCodes;

import static com.inspur.edp.cef.designtime.api.validate.common.CheckUtil.exception;
import static com.inspur.edp.cef.designtime.api.validate.common.CheckUtil.isLegality;

public class ActionChecker {
    private static ActionChecker actionChecker;

    public static ActionChecker getInstance() {
        if (actionChecker == null) {
            actionChecker = new ActionChecker();
        }
        return actionChecker;
    }

    protected final void opException(String code) {
        if (code == null || code.isEmpty())
            return;
        exception(code);
    }

    public void checkVMAction(GspViewModel vm) {
        for (ViewModelAction vmAction : vm.getActions()) {
            actionCodeInspaction(vmAction);
            parametersInspaction(vmAction);
        }
    }

    private void actionCodeInspaction(ViewModelAction vmAction) {
        if (vmAction == null)
            return;
        if (StringUtils.isEmpty(vmAction.getCode())) {
            throw new ViewModelException(VoManagerErrorCodes.GSP_VIEWOBJECT_MANAGER_0073, null, vmAction.getName());
        }
        if (isLegality(vmAction.getCode()))
            return;
        throw new ViewModelException(VoManagerErrorCodes.GSP_VIEWOBJECT_MANAGER_0074, null, vmAction.getCode());
    }

    private void parametersInspaction(ViewModelAction action) {
        for (Object par : action.getParameterCollection()) {
            par = par instanceof MappedCdpActionParameter ? (MappedCdpActionParameter) par : null;
            if (par == null)
                continue;
            if (StringUtils.isEmpty(((MappedCdpActionParameter) par).getParamCode())) {
                throw new ViewModelException(VoManagerErrorCodes.GSP_VIEWOBJECT_MANAGER_0075, null, action.getCode(), ((MappedCdpActionParameter) par).getParamName());
//                opException("视图对象["+action.getCode()+"]的动作参数["+((MappedCdpActionParameter) par).getParamCode()+"]不能为空,请修改！");
            }
            if (isLegality(((MappedCdpActionParameter) par).getParamCode()))
                continue;
            throw new ViewModelException(VoManagerErrorCodes.GSP_VIEWOBJECT_MANAGER_0076, null, action.getCode(), ((MappedCdpActionParameter) par).getParamCode());
//            opException("视图对象["+action.getCode()+"]的动作参数["+((MappedCdpActionParameter) par).getParamCode()+"]是Java关键字,请修改！");
        }
    }
}
